connectionId = 0

Procedure Die(Message.s)
  MessageRequester("Fatal Error", Message)
EndProcedure


Procedure SendMessageToFitnesse(Message.s)
  Shared connectionId
  ProcedureReturn SendNetworkData(ConnectionId, @Message, Len(Message))
EndProcedure

Procedure SendIntegerToFitnesse(value)
  ProcedureReturn SendMessageToFitnesse(Right("0000000000" + Str(value),10))
EndProcedure

Procedure SendCountsToFitnesse(right, wrong, ignores, exceptions)
  SendIntegerToFitnesse(right)
  SendIntegerToFitnesse(wrong)
  SendIntegerToFitnesse(ignores)
  SendIntegerToFitnesse(exceptions)
EndProcedure

Procedure.s ReceiveFromFitnesse(Size)
  Shared connectionId
  
  *Buffer = AllocateMemory(Size)
  Received = ReceiveNetworkData(connectionId, *Buffer, Size)
  Response.s = PeekS(*Buffer, Received)
  FreeMemory(*Buffer)
  
  ProcedureReturn Response
EndProcedure

Procedure IntegerBlock()
  IntegerBlock.s = ReceiveFromFitnesse(10)
  
  If IntegerBlock = "0000000000"
    ;Test for 0 explicitly, since Val will return 0 for a badly formed block.
    ProcedureReturn 0
  Else
    IntegerValue = Val(IntegerBlock)
    If IntegerValue > 0
      ProcedureReturn IntegerValue
    Else
      ;We have already tested for a valid 0.  This must be an error.
      Die("Bad integer block:"+integerblock)
    EndIf
  EndIf
EndProcedure

Procedure Connect(host.s, port, ticket)
  Shared connectionId
  Message.s = "GET /?responder=socketCatcher&ticket="+Str(ticket)+" HTTP/1.1"+#CRLF$+#CRLF$
  
  ConnectionId = OpenNetworkConnection(host, port)
  If connectioniD > 0
    Result = SendNetworkData(ConnectionId, @Message, Len(Message))
    If Result = Len(Message)
      Response = IntegerBlock()
    EndIf
  Else
    Die("Ticket " + Str(ticket) + " was not accepted by " + host + ":" + Str(port))
  EndIf
  
  ProcedureReturn Response
EndProcedure

Procedure Transact()
  documentSize = IntegerBlock()
  While documentSize > 0
    document.s = ReceiveFromFitnesse(documentSize)
    MessageRequester(Str(documentSize), document)
    SendIntegerToFitnesse(documentSize)
    SendMessageToFitnesse(document)
    SendIntegerToFitnesse(0)
    SendCountsToFitnesse(1, 2, 3, 4)
    documentSize = IntegerBlock()
  Wend
EndProcedure

Procedure Close()
  
  CloseNetworkConnection(ConnectionId)
EndProcedure

If InitNetwork() 

  host.s = ProgramParameter()
  port.s = ProgramParameter()
  ticket.s = ProgramParameter()
  
  Connect(host, Val(port), Val(ticket))
  Transact()
  Close()
  
  

EndIf
; IDE Options = PureBasic 3.94 (Linux - x86) - (c) 2005 Fantaisie Software
; CursorPosition = 20
; Folding = --
; Executable = PbFitServer.exe